package com.tanhua.admin.service;

import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.admin.exception.BusinessException;
import com.tanhua.admin.mapper.AdminMapper;
import com.tanhua.commons.utils.Constants;
import com.tanhua.commons.utils.JwtUtils;
import com.tanhua.model.db.Admin;
import com.tanhua.model.vo.AdminVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.security.Security;
import java.util.HashMap;
import java.util.Map;

@Service
public class AdminService {

    @Autowired
    private AdminMapper adminMapper;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;


    //用户登录 --校验验证码
    public Map login(String username, String password, String verificationCode, String uuid) {

        //1 判断验证码是否一致
        String code = redisTemplate.opsForValue().get(Constants.CAP_CODE + uuid);

        if (StringUtils.isEmpty(code) || !code.equals(verificationCode)){
            throw  new BusinessException("验证码不正确");
        }
        //从redis中删除
        redisTemplate.delete(Constants.CAP_CODE + uuid);

        //2 根据username从数据库查询是否存在
        QueryWrapper<Admin> wrapper=new QueryWrapper<>();
        wrapper.eq("username",username);
        Admin admin = adminMapper.selectOne(wrapper);


        //3 如果不存在或者密码密码不正确 返回错误信息
        //对密码进行加密后在比较
        password = SecureUtil.md5(password);
        System.out.println(password);

        if (admin==null || !password.equals(admin.getPassword())){
            throw  new BusinessException("用户名或者密码错误");
        }

        //4 若密码正确 构造token并返回
        Map map=new HashMap();
        map.put("id",admin.getId());
        map.put("username",admin.getUsername());
        String token = JwtUtils.getToken(map);

        //构造返回
        Map resMap=new HashMap();
        resMap.put("token",token);
        System.out.println(token);

        return resMap;
    }

    //用户基本信息
    public Admin profile(Long userId) {

        Admin admin = adminMapper.selectById(userId);

        return admin;
    }
}
